<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索添加-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--表格-->
      <el-table :data="userList" border stripe>
        <el-table-column label="##" type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>

        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="userStareChange(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="removeUserById(scope.row.id)"></el-button>

            <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!--添加用户-->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        @close="addDialogClose"
        width="50%">

        <!--内容操作-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
      </el-dialog>

      <!--修改用户-->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        @close="editDialogClose"
        width="50%">

        <!--内容操作-->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser()">确 定</el-button>
  </span>
      </el-dialog>

      <!--权限操作-->
      <el-dialog
        title="权限分配"
        :visible.sync="roleUserdialogVisible"
        width="50%">
        <div>
          <p>当前用户: {{userinfo.username}}</p>
          <p>当前角色: {{userinfo.role_name}}</p>
          <p>分配新角色:
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>

        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="roleUserdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  export default {
    data () {
      // 校验邮箱
      var checkEmail = (rule, value, cb) => {
        const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (regEmail.test(value)) {
          return cb()
        }
        return cb(new Error('请输入合法邮箱'))
      }
      // 校验手机号
      var checkMobile = (rule, value, cb) => {
        const regMobile = /^1[3456789]\d{9}$/
        if (regMobile.test(value)) {
          return cb()
        }
        return cb(new Error('请输入合法手机号'))
      }
      return {
        queryInfo: {
          query: '',
          pagenum: 1, // 页数
          pagesize: 10 // 条数
        },
        userList: [],
        total: 0,
        addDialogVisible: false,
        editDialogVisible: false,
        // 添加用户
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 修改用户
        editForm: {
          username: '',
          email: '',
          mobile: ''
        },
        addFormRules: {
          username: [
            {
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 15,
              message: '长度在 5 到 15 个字符',
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: '请输入用户密码',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 15,
              message: '长度在 6 到 15 个字符',
              trigger: 'blur'
            }
          ],
          email: [
            {
              required: true,
              message: '请输入用户邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [
            {
              required: true,
              message: '请输入用户手机号',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        },
        editFormRules: {
          email: [
            {
              required: true,
              message: '请输入用户邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [
            {
              required: true,
              message: '请输入用户手机号',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        },
        userinfo: {},
        roleList: {},
        selectRoleId: '',
        roleUserdialogVisible: false // 分配权限
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      async getUserList () {
        const { data: res } = await this.$http.get('users', { params: this.queryInfo })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.userList = res.data.users
        this.total = res.data.total
      },
      // 每页多少条
      handleSizeChange (pageNum) {
        console.log(pageNum)
        this.queryInfo.pagesize = pageNum
        this.getUserList()
      },
      // 到第几页
      handleCurrentChange (pageChange) {
        console.log(pageChange)
        this.queryInfo.pagenum = pageChange
        this.getUserList()
      },
      // 状态修改
      async userStareChange (data) {
        const { data: res } = await this.$http.put(`users/${data.id}/state/${data.mg_state}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
      },

      // 监听对话框关闭
      addDialogClose () {
        this.$refs.addFormRef.resetFields()
      },
      // 添加用户
      addUser () {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return false
          const { data: res } = await this.$http.post('users', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
            this.addDialogVisible = false
            this.getUserList()
          }
        })
      },
      // 展示编辑
      async showEditDialog (id) {
        const { data: res } = await this.$http.get('users/' + id)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editForm = res.data
        this.editDialogVisible = true
      },
      // 修改用户信息
      editUser () {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return false
          const { data: res } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
            this.editDialogVisible = false
            this.getUserList()
          }
        })
      },
      // 监听修改框关闭
      editDialogClose () {
        this.$refs.editFormRef.resetFields()
      },
      // 删除用户操作
      async removeUserById (id) {
        console.log(id)
        // 弹窗
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(msg => {
          return msg
        }).catch(err => {
          return err
        })

        if (confirmResult !== 'confirm') {
          return this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }

        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.$message.success(res.meta.msg)
          this.getUserList()
        }
      },
      // 分配权限操作
      async setRole (row) {
        this.userinfo = row
        console.log(row)
        // 获取权限列表
        const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.roleList = res.data
        this.roleUserdialogVisible = true
      },
      // 保存新分配的角色
      async saveRoleInfo () {
        if (!this.selectRoleId) return this.$message.error('请先选择角色')
        const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectRoleId })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.selectRoleId = ''
        this.roleUserdialogVisible = false
        this.getUserList()
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-table {
    margin: 12px;
    font-size: 12px;
  }
</style>
